package com.gofaraway.common.domin;

import com.gofaraway.common.exception.v2.BaseErrorInfo;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenPeng
 * @Date 2024/7/24 16:20
 */
@Data
public class ResultDTO<T> implements Serializable {
    private static final long serialVersionUID = 5646124233793153393L;
    /**
     * 错误code
     */
    private String errorCode;
    /**
     * 错误信息
     */
    private String errorMsg;
    /**
     * 返回的数据
     */
    private T data;
    /**
     * 附加信息
     */
    private Map<String, Object> extraInfo;

    /**
     * 注：元参构造器仅用于序列化，请根据成功或失败情况使用应对的静态工厂方法，勿直接使用构造器
     */
    public ResultDTO() {
    }

    private ResultDTO(BaseErrorInfo baseErrorInfo) {
        this.errorCode = baseErrorInfo.getErrorCode();
        this.errorMsg = baseErrorInfo.getErrorMessage();
    }

    private ResultDTO(T data) {
        this.data = data;
    }

    public static <T> ResultDTO<T> ofSuccess(T data) {
        return new ResultDTO<>(data);
    }

    public static <T> ResultDTO<T> ofError(BaseErrorInfo baseErrorInfo) {
        return new ResultDTO<>(baseErrorInfo);
    }

    public ResultDTO<T> withExtraInfo(String key, Object value) {
        if (extraInfo == null) {
            extraInfo = new HashMap<>(4);
        }
        extraInfo.put(key, value);
        return this;
    }

    public boolean isSuccess() {
        return StringUtils.isBlank(errorCode);
    }
}
